<template>
  <div>
    <div>
      <input v-model="keyword" />
    </div>
    <el-tree
      :data="departmentMemberTreeData"
      :props="defaultProps"
      :load="getDepartmentMemberTreeDataAsync"
      lazy
      @node-click="departmentMemberTree_clickNode"
    ></el-tree>
  </div>
</template>

<script>
import axios from "axios";
import { debounce } from 'throttle-debounce';

export default {
  data() {
    return {
      keyword: "",
      currentMember: "",
      departmentMemberTreeData: [],
      defaultProps: {
        label: "nodeName",
        isLeaf: function(data) {
          return !data.hasChild;
        }
      },
      cacheLevel0Data: []
    };
  },
  watch: {
    keyword(val) {
      this.grantGroupDeptMemberAsyncTreeSearch(val);
    }
  },
  methods: {
    // 异步获取部门员工树
    getDepartmentMemberTreeDataAsync(node, resolve) {
      let params = {
        appId: "590",
        showMember: 1
      };
      if (node.level > 0) {
        if (node.data.nodeType !== 1 && node.data.hasChild) {
          params.nodeId = node.data.nodeId;
        } else {
          // 如果是员工节点，直接返回
          return;
        }
      }

      axios
        .get(
          "http://172.31.119.38:35002/roc/accessweb/web/org/grantGroupDeptMemberAsyncTree",
          {
            headers: {
              "X-Access-Source": "roc",
              "X-Access-Token": "8f397a6addf533bca0a084f7f4a35347"
            },
            params
          }
        )
        .then(res => {
            if (node.level === 0) {
                this.cacheLevel0Data = res.data.data.slice(0)
            }
          resolve(res.data.data);
        });
    },
    // 部门员工树节点点击
    departmentMemberTree_clickNode(data, clickNode) {
      if (data.nodeType === 1) {
        this.currentMember = data.nodeId
      }
    },
    grantGroupDeptMemberAsyncTreeSearch: debounce(500, false, function (val) {
        if(!val) {
            this.departmentMemberTreeData = this.cacheLevel0Data.slice(0)
            return;
        }
        let params = {
            appId: "590",
            hasMember: 1,
            hasEmptyDept: 0,
            keyword: val
        }
        axios.get("http://172.31.119.38:35002/roc/accessweb/web/org/grantGroupDeptMemberAsyncTreeSearch",
          {
            headers: {
              "X-Access-Source": "roc",
              "X-Access-Token": "8f397a6addf533bca0a084f7f4a35347"
            },
            params
          }
        )
        .then(res => {
          this.departmentMemberTreeData = res.data.data
        })
    })
  }
};
</script>

<style lang="scss" scoped>
</style>